package zhoujunhao.rbac.service.array;

import zhoujunhao.rbac.domian.dto.BaseDto;
import zhoujunhao.rbac.domian.entity.BaseEntity;
import zhoujunhao.rbac.domian.vo.BaseVo;
import zhoujunhao.rbac.domian.vo.Result;
import zhoujunhao.rbac.service.IBaseService;

import java.util.Arrays;

/**
 * 业务层-基类
 *
 * @author 周均壕
 * @since 2025/6/16 20:59
 */
 abstract class BaseService<
        Entity extends BaseEntity, Dto extends BaseDto, Vo extends BaseVo> implements
        IBaseService<Entity, Dto> {


    static final int DATA_SIZE = 100;

    Entity[] date;
    Vo[] temp;

    private int idcounter = 1;

    @Override
    public boolean existsByid(int id) {

        return id >= 1 && id < idcounter && date[id] != null;
    }

    @Override
    public Entity findById(int id) {
        if (existsByid(id)) {
            return date[id];
        }
        return null;
    }


    abstract Vo convertToVo(Entity entity);

    @Override
    public Result list() {
        int length = 0;
        for (int i = 1; i < idcounter; i++) {
            if (date[i] != null) {
                temp[length++] = convertToVo(date[i]);
            }
        }
        return Result.success("查询成功", Arrays.copyOf(temp, length));
    }

    abstract Entity createEntity(Dto dto, int id);

    @Override
    public Result create(Dto dto) {
        if (idcounter > DATA_SIZE) {
            return Result.failure("创建失败，超出容量");
        }
        Entity entity = createEntity(dto, idcounter++);
        date[entity.getId()] = entity;
        return Result.success("创建成功", null);
    }

    abstract void updateEntity(Dto dto, Entity entity);

    @Override
    public Result update(Dto dto, int id) {
        if (!existsByid(id)) {
            return Result.failure("更新失败，部门不存在");
        }
        Entity entity = date[id];
        updateEntity(dto, entity);
        return Result.success("更新成功", null);
    }
}
